

var path = "";
var _sessionId = "";
var url = "";
var connId = "";
var transferConnId="";
var serverUrl = "10.128.64.70:8090";
// 拨打电话地址
var callUrl = "http://"+serverUrl+"/api/v1/me/calls/";
// 初始化channel地址
var initChannelUrl = "http://"+serverUrl+"/api/v1/me/channel/";
// 初始化所有channel
var initAllChannelUrl = "http://"+serverUrl+"/api/v1/me/channels/";
var heartbeatUrl="http://"+serverUrl+"/api/v1/me/heart";

var place = "6005";
var loginCode = "10002";

_sessionId = sessionId;
alert(_sessionId);
connectWebsocket();
/**
 * 心跳监测定时器
 */
var heartCheck = {
    timeout: 30000,//60ms
    timeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        this.start();
    },
    start: function(str){
        this.timeoutObj = setInterval(function(){
            AjaxHeartBeatGet(str);
            if(websocket!=null){
                if(websocket.readyState!=1){
                    connectWebsocket();
                }
                websocket.send("heartCheck");
            }
            log(new Date()+"------heartCheck:"+str);
        }, this.timeout)
    }
}
function connectWebsocket(){
    websocket = new WebSocket("ws://"+serverUrl+"/websocket/softphone/"+_sessionId);


    //连接发生错误的回调方法
    websocket.onerror = function(){
        log(" websocket.onerror :error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        log(" websocket.onopen :open",event);
        try{
            AjaxHeartBeatGet(heartbeatUrl+"/"+place+"/"+loginCode);
            log(new Date()+"------heartCheck:"+heartbeatUrl+"/"+place+"/"+loginCode);
            heartCheck.start(heartbeatUrl+"/"+place+"/"+loginCode);
            log("-----heartCheck:",heartCheck.timeoutObj);
        }catch (e) {
            log("-----heartCheck error:",e);
        }
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        log("websocket.onmessage is:",event.data);
        echoRpcReturn(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        log(" websocket.onclose :close");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }
}

function AjaxHeartBeatGet(url){
    var result;
    $.ajax( {
        url : url,
        type : "GET",
        async : false,
        timeout : 1000,
        error : function(jqXHR, textStatus, errorThrown) {
        },
        success : function(data) {

            // showButtons(result.type);
            result = data;
        }

    });
    return result;
}

function log(msg, obj) {
    if(obj){
        console.log(msg, obj);
    }else{
        console.log(msg);
    }
}

/**
 * echoRpcReturn cometd回调方法
 *
 * @param msg
 * @return
 */
function echoRpcReturn(msg) {
    // alert(msg.data.msg);
    log("echoRpcReturn message is:"+new Date(),msg);
    var reseMsg;
    var eventName ='';
    if('WebSocket' in window){
        var logDiv = document.getElementById("responses");
        logDiv.innerHTML += new Date() + ":\n" + msg + "\n";
        logDiv.scrollTop = logDiv.scrollHeight;
        msg = eval('(' + msg + ')');
        if(msg.referenceId != undefined){
            log(msg.referenceId+"----");
            retrunAckMsg(msg.referenceId);
        }
        log("msg.data is:"+new Date(),msg.data);
        var reseMsg = msg;
        log("reseMsg is:",reseMsg);
    }else{
        var div = dojo.byId("responses");
        dojo.byId("responses").innerHTML += new Date() + ":\n" + msg.data + "\n";
        div.scrollTop = div.scrollHeight;
        log(msg.data);
        reseMsg = eval('(' + msg.data + ')');
    }


    if(reseMsg!=null&&reseMsg!=''&&reseMsg!='undefined'){
        if (reseMsg.data&&reseMsg.data.messageType == "DeviceStateChangeMessage") {
            handleAgentStatusChanged(reseMsg.data.devices);
        } else if (reseMsg.data&&reseMsg.data.messageType&&reseMsg.data.messageType == "CallStateChangeMessage") {
            CallStateChangeMessage(reseMsg.data);
        } else if (reseMsg.messageType&&reseMsg.messageType == "ChatStateChangeMessage") {
            chatStateChangeMessage(reseMsg.chat);
        } else if (reseMsg.messageType&&reseMsg.messageType == "MessageLogUpdated") {
            chatMessageReceive(reseMsg);
        } else if (reseMsg.messageType&&reseMsg.messageType == "ErrorMessage") {
            callMessageError(reseMsg);
        }
    }
}